import java.util.Arrays;
import java.util.Scanner;

/**
 * Created by IntelliJ IDEA.
 * User: zm
 * Date: 2023/5/30
 */
public class Main {
    static int N = 510,n,m,max = 0x3f3f3f;
    static int[][] g = new int[N][N];//存放两点之间的距离
    static int[] dist = new int[N];
    static boolean[] st = new boolean[N];
    public static int dijkstra(){
        Arrays.fill(dist,max);
        dist[1] = 0;
        for(int i = 0; i < n; i++){
            int t = -1;
            for(int j = 1; j <= n; j++){
                if(!st[j] && (t == -1 || dist[j] < dist[t])){
                    t = j;
                }
            }
            st[t] = true;
            for(int j = 1; j <= n; j++){
                dist[j] = Math.min(dist[j],dist[t] + g[t][j]);//遍历每一个数字,没链接的默认最大值
            }
        }
        if(dist[n] == max)return -1;
        else return dist[n];
    }

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        n = scan.nextInt();
        m = scan.nextInt();
        for(int i = 1; i <= n; i++) Arrays.fill(g[i],max);

        while(m -- > 0){
            int a = scan.nextInt();
            int b = scan.nextInt();
            int c = scan.nextInt();
            g[a][b] = Math.min(g[a][b],c);//这个因为可能存在重边，所以泽出最短的
        }
        int res = dijkstra();
        System.out.println(res);
    }
}
